import { reactive, computed, inject } from 'vue'
import { defineStore } from 'pinia'
import { socket } from '../utils/websocket'

export const useWsuserStore = defineStore('wsuser', () => {
  const account = reactive({
    id: '',
    name: 'world',
    role: ''
  })
  const user = computed(() => {
    const { name } = account
    return name
  })

  const login = (params) => {
    let promise = socket('ws://localhost:3000/users/logon', params)
    promise.then((packet) => {
      account.id = packet.data.id
      account.name = packet.data.name
      account.role = packet.data.role
    })
    return promise
  }

  const close = () => {
    socket.close()
  }

  return { account, user, login, close }
})
